import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { listCv,getCv,addCv,updateCv,delCv,uploadCv} from "@/api/modules/cv";
import { upload } from "@/api/modules/common";

const Cv = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [onReloadNum,setOnReloadNum] = useState(null)

  const formColumns = []

  const columns: any = [
    {
      title: t('cv.serial'),
      dataIndex: 'serial',
      key: 'serial',
      fixed:'left',
    },
    {
      title: t('cv.name'),
      dataIndex: 'name',
      key: 'name',
      fixed:'left',
    },
    {
      title: t('cv.dept'),
      dataIndex: 'dept',
      key: 'dept',
    },
    {  
      title: t('action'),  
      key: 'action',  
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleDownload(record)}>  
           {t('download')}  
          </Button> 
          <Button type="link" onClick={() => handleEdit(record)}>  
          {t('edit')}  
          </Button>  
          <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>  
   
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await listCv({...formData, orderby: 'id', order: 0})
    if(!success) return false
    console.log(data)
    const list = data.rows
    return {
      data: list,
      total: data.total
    }
  } 

  const handleAdd = () =>{
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    const { file } = values;  
    let formData = new FormData();
    const data = form.getFieldsValue()
    console.log(file,'file')
    if(values.file==null || values.file == undefined || values.file == ""){
          formData.append("file", null);
      }else{
          const file1 = values.file.originFileObj
          formData.append('file',file1); // 假设file.file是选中的文件对象  
      }
    if(Title=='新增/New'){
       
    }else{
        formData.append("id", values.id);
    }
    formData.append("name", values.name);
    formData.append("serial", values.serial);
    formData.append("dept", values.dept);
    if(Title=='新增/New'){
        //新增
        uploadCv(formData).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        updateCv(values).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleDownload = (row) =>{
    download("safety/cv/downLoadCv?id="+row.id, {
     
    }, `${row.name}.docx`);
  }

  const handleEdit = (record) =>{
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delCv(key).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const beforeUpload = (file) => {  
   
  };  

const handleFileChange = (info) => { 
    console.log(info,'info') 
    form.setFieldsValue({  
        file: info.file,  
      }); 
  };  

  const renderOperator = <>
    <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>
  
  return (
    <div> 
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
          destroyOnClose
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled />  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="serial"  
              label={t('cv.serial')}  
            >  
              <Input/>  
            </Form.Item>  
            <Form.Item  
              name="name"  
              label={t('cv.name')}  
              rules={[{ required: true, message: '请输入名称！' }]}  
            >  
              <Input/>  
            </Form.Item>  
            <Form.Item  
              name="dept"  
              label={t('cv.dept')}  
            >  
              <Input/>  
            </Form.Item>  
            <Form.Item  
                name="file"  
                label={t('cv.file')}
            >  
                <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                    // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                    // 例如，使用axios发送POST请求上传文件  
                    // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                beforeUpload={beforeUpload}  
                onChange={handleFileChange} 
                >  
                <Button icon={<UploadOutlined />}>{t('cv.file')}</Button>  
                </Upload>  
            </Form.Item>
          </Form>  
        </Modal>  
    </div>
  )
}
export default Cv
